<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 修改固件
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>
      <Form
        ref="formValidate"
        :model="bloc.firmwareId"
        :rules="ruleValidate"
        :label-width="100"
        style="padding:50px 12% 0 10%;width:1000px"
      >
        <FormItem label="设备分类：" prop="sortId" :label-width="120" style="display: none" required>
          <Select v-model="bloc.firmwareId.sortId" @on-change="handleChange(bloc.firmwareId.sortId)" disabled>
            <Option
              v-for="(item,index) in bloc.sortList"
              :value="item.id"
              :key="index"
            >{{ item.sortName }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="设备型号：" prop="modelId" :label-width="120" style="display: none" required>
          <Select v-model="bloc.firmwareId.modelId" disabled>
            <Option
              v-for="(item,index) in bloc.modelList"
              :value="item.id"
              :key="index"
            >{{ item.modelName }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="固件版本号：" prop="versions" :label-width="120" style="position: relative;" required>
          <input v-model="bloc.firmwareId.versions" style="width: 400px;" disabled
                 class="version"><span
          style="position: absolute;width: 32px;left:0;text-align: center">v</span>
        </FormItem>

        <FormItem label="添加固件：" prop="url" :label-width="120" required>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="10240"
            :format="['bin']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
          >
            <Button icon="ios-filing">选择固件</Button>
          </Upload>
          <a v-if="bloc.firmwareId.extName" :href="bloc.firmwareId.url">{{bloc.firmwareId.extName}}</a>

          <p style="margin-left: 15px">支持文件格式:.bin，单个文件不能超过10MB</p>
        </FormItem>

        <!--<FormItem label="对于固件版本号：" required>
          <Input type="text" v-model="bloc.firmwareId.versions"/>
        </FormItem>
        -->

        <FormItem label="固件状态：" :label-width="120" required>
          <i-switch @on-change="switchStatus"
                    v-model="enable"></i-switch>
        </FormItem>
        <FormItem label="固件详情：" prop="describe" :label-width="120" required>
          <Input type="textarea" v-model="bloc.firmwareId.describe" :rows='5' maxlength="50" show-word-limit
                 style="width: 400px"></Input>
        </FormItem>
        <!--        固件ID：-->
        <FormItem label="">
          <!--          <Input v-model="bloc.firmwareId.id" type="hidden"></Input>-->
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <Button
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="btnload.loading"
          style="margin-left: 30px;width: 100px;height: 40px;"
        >保存
        </Button>
      </div>
    </Card>
  </div>
</template>
<script lang="ts">
  import {Component, Prop, Vue} from 'vue-property-decorator';
  import {FirmwareBloc} from './FirmwareBloc';
  import {store} from '@/store/Store';
  import {baseUrl} from '@/base/Request';
  import {Loading} from '@/base/Loading';

  @Component({
    components: {}
  })
  export default class extends Vue {
    @Prop({type: Number})
    readonly init!: number;
    bloc = new FirmwareBloc();
    btnload = new Loading()
    formValidate: any = {
      type: '',

      switch: true
    };

    ruleValidate: any = {
      describe: [
        {required: true, message: '固件详情不能为空', trigger: 'blur'}
      ],
      modelId: [
        {required: true, message: '设备型号不能为空', trigger: 'change', type: 'number'}
      ],
      sortId: [
        {required: true, message: '设备分类不能为空', trigger: 'change', type: 'number'}
      ],
      url: [
        {required: true, message: '固件文件不能为空', trigger: 'blur'}
      ],
      // versions: [
      //   {required: true, message: '固件版本不能为空', trigger: 'blur'}
      // ]
    };
    $refs!: {
      formValidate: HTMLFormElement
    }

    get enable() {
      if (this.bloc.firmwareId.issueStatus === 'ISSUE') {
        return true;
      } else {
        return false;
      }
    }

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      }
    };

    get uploadAction() {
      return `${baseUrl}/api/upload/packet`
    }

    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc:
          file.name +
          ' 文件格式不正确，请选择格式为.bin格式的文件'
      });
    }

    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出了文件大小限制',
        desc: file.name + ' 文件太大，不能超出10M'
      });
    }

    handleChange(sortId) {
      this.bloc
        .getAllModel(this.bloc.page.pageIndex, this.bloc.page.pageSize, sortId, 'ASC', undefined)
        .then(res => {
        })
        .finally(() => {
          this.bloc
            .getAllSort(this.bloc.page.pageIndex, this.bloc.page.pageSize, 'ASC')
        });
    }

    handleSuccess(res, file) {
      this.bloc.firmwareId.url = res.data.url
      this.bloc.model.extName = file.name
    }

    queryFirmware() {
      this.bloc.getAllSort(this.bloc.page.pageIndex, this.bloc.page.pageSize, 'ASC')
      var id = Number(this.$route.params.id);
      this.bloc.toModifyItem(id)
    }

    switchStatus(status) {
      if (status) {
        this.bloc.firmwareId.issueStatus = 'ISSUE'
      } else {
        this.bloc.firmwareId.issueStatus = 'ISSUE'
      }
    }

    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.btnload.loading = true;
          this.bloc.modifyItem(this.bloc.firmwareId.describe, this.bloc.firmwareId.id, this.bloc.firmwareId.issueStatus,
            this.bloc.firmwareId.modelId, this.bloc.firmwareId.sortId, this.bloc.firmwareId.url)
            .then(res => {
              this.$Message.success('保存成功');
              this.$router.push({
                path: '/device/nav/firmware/' + this.$route.query.id,
                query: {sortId: this.$route.query.sortId}
              });
              if (res.message !== '') {
                this.$Message.error(res.message);
              }
            })
            .catch(err => {
              console.log('save failed.', err);
              this.$Message.error(err.message);
            })
            .finally(() => {
              this.btnload.loading = false;
            })
        }
      })
    }

    handleCancel() {
      this.$router.push({
        path: '/device/nav/firmware/' + this.$route.query.id,
        query: {sortId: this.$route.query.sortId}
      });
    }

    mounted() {
      this.queryFirmware()
      this.bloc.getModel(Number(this.$route.query.id))
        .then(res => {
          this.bloc.model.sortId = res.data.sortId
          this.bloc.model.modelId = res.data.id
          this.bloc.modelList = [{id: res.data.id, modelName: res.data.modelName}]
        })
    }
  }
</script>
<style lang="less" scoped>
  .top {
    height: 50px;
    width: 100%;
    border-bottom: 1px solid rgba(204, 204, 204, 1);
    font-size: 18px;
    line-height: 50px;
  }

  /deep/ .ivu-form-item-content {
    display: flex !important;
    justify-content: start !important;
    align-items: center !important;
  }
</style>
